// pages/myOrderDetail/myOrderDetail.js订单详情
let url_js = require("../../utils/url.js");
let common_js = require("../../utils/common.js");
let const_js = require("../../utils/const.js");
let user_js = require("../../utils/user.js");
let ubt_js = require("../../utils/ubt.js");
let name_js = require("../../utils/ubtButtonName.js");
let page_js = require("../../utils/pageOptions.js");
let api = require("../../utils/apiRequest.js");
let wxp = require("../../utils/wxp.js");

Page({

  /**
   * 页面的初始数据
   */
  data: {
    orderId: '',
    orderListStatus: null, //订单列表传过来的状态，如果有的话更新上个页面的数据
    userInfo: null,
    item: null,
    topDes: "",
    isPintDetailShow: false,
    contentStatus: -1,
    shareInfo: '',
    isPhoneShow: false,
    isCouponViewShow: false,
    pageScrollTop: 0,
    containerTouchmove: '',
    newUserCouponInfo: [], //下完订单展示券
    leftTime:1000
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //业务埋点
    ubt_js.myPageView(common_js.currentPageName(), options);
    //0.禁止转发
    wx.hideShareMenu();
    //1.初始化数据
    this.initData(options);
  },
  //分享信息
  onShareAppMessage(res) {
    return {
      title: this.data.shareInfo.shareTitle,
      imageUrl: this.data.shareInfo.shareImag,
      path: `/pages/shareCoupon/shareCoupon?orderId=${this.data.orderId}`
    }
  },
  //判断是否显示分享优惠券弹窗
  getsetting() {
    api.wxRequest2(url_js.getsetting, {
      orderId: this.data.orderId
    }).then(res => {
      if (res.code === 200 && res.result && res.result.dealCampaign && res.result.dealCampaign.id) {
        this.setData({
          shareInfo: res.result.dealCampaign
        })
        api.wxRequest(url_js.refreshsharecoupon, {
          orderId: this.data.orderId
        }).then(res => {
          if (res.code === 200) {

          }
        }).catch(err => {
          common_js.log(err);
        });
      }
    }).catch(err => {
      common_js.log(err);
    });
  },
  //控制优惠券弹窗是否显示
  hideBox() {
    this.setData({
      shareInfo: this.data.shareInfo ? false : true
    })
  },


  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    // 业务埋点
    ubt_js.myPageViewOut(common_js.currentPageName());
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    //如果是分享进来的，并且没有选择角色，进入角色选择页面
    if (page_js.pageOptionsInfo()) {
      //2.relauch
      wx.reLaunch({
        url: '../indexSearchShop/indexSearchShop'
      });
    }
  },

  //初始化数据
  initData: function (options) {
    //1.更新userInfo
    let tmpOrderId = options.orderId ? options.orderId : '';
    //没有角色--->角色选择
    if (!user_js.hasRole()) {
      //1.save param
      let obj = {
        url: '../myOrderDetail/myOrderDetail',
        param: '?orderId=' + tmpOrderId
      }
      page_js.savePageOptionsInfo(obj);
      //2.relauch
      //*********跳转放在onshow
      return;
    } else {
      //有角色，展示页面
      this.initUnShareOptionsData(options);
      //2.请求数据
      this.requestToGetOrderInfo(this.data.orderId);
    }
  },

  //初始化数据
  initUnShareOptionsData: function (options) {
    //1.更新userInfo
    let tempUserInfo = user_js.userInfo();
    let tmpOrderId = options.orderId ? options.orderId : '';
    let tmpStatus = options.status ? options.status : null;

    this.setData({
      orderId: tmpOrderId,
      orderListStatus: tmpStatus,
      userInfo: tempUserInfo
    });
  },

  //请求数据
  requestToGetOrderInfo: function (orderId) {
    let requestList = [];
    //1.订单详情
    let data = {
      cityId: this.data.userInfo.ztd.cityId,
      code: user_js.getCode(),
      orderId: orderId,
      shopId: this.data.userInfo.ztd.id
    }
    requestList.push(api.wxRequest(url_js.orderInfoUrl, data));
    requestList.push(api.wxRequest(url_js.newUserActivityShowOrderCouponUrl, data));
    //获取数据
    Promise.all(requestList).then(results => {
      this.handleOrderInfoData(results[0]);
      this.handleOrderCouponData(results[1]);
    }).catch(err => {
      common_js.log(err);
    });
  },

  // 倒计时
  countDown: function () {
    var that = this;
    var time = parseInt(that.leftTime)
    // debugger;
    let min = parseInt(time / 60);
    let sec = parseInt(time % 60);
    
    min = that.timeFormin(min),
    sec = that.timeFormin(sec);
    that.leftTime = that.leftTime - 1
    that.setData({
      min: that.timeFormat(min),
      sec: that.timeFormat(sec)
    })
    // 每1000ms刷新一次
    if (time > 0) {
      that.setData({
        countDown: true
      })
      setTimeout(this.countDown, 1000);
    } else {
      that.setData({
        countDown: false
      })
      /// 倒计时结束, 重新请求数据
      that.requestToGetOrderInfo(that.data.orderId);
    }
  },
  //小于10的格式化函数（2变成02）
  timeFormat(param) {
    return param < 10 ? '0' + param : param;
  },
  //小于0的格式化函数（不会出现负数）
  timeFormin(param) {
    return param < 0 ? 0 : param;
  },

  //处理返回的数据
  handleOrderInfoData: function (res) {
    // debugger;
    let des = this.getTopDes(res.result);
    let tmpItem = res.result;
    let leftTime = res.result.leftTime
    /// 如果需要显示倒计时, 且倒计时时间大于0
    if(res.result.status == 1 && leftTime != null && parseInt(leftTime) > 0) {
      this.leftTime = leftTime;
      this.countDown();
    }
    tmpItem.sxSkuList.forEach((item, index) => {
      item.type = tmpItem.type;
    });
    //计算实际支付金额
    let tmpActualPayment = (tmpItem.totalAmount - tmpItem.couponAmount).toFixed(2);
    tmpItem.actualPayment = tmpActualPayment;

    this.setData({
      contentStatus: 1,
      topDes: des,
      item: res.result
    });
    let _time = this.data.item.createTime.replace(/-/g, "/");
    let timeStamp = +new Date(_time);
    //支付完成(待提货状态)判断是否需要分享领券(下单超过1小时不显示)
    this.data.item.status >= 3 && +new Date() - timeStamp < 60 * 60 * 1000 && this.getsetting();

    //待提货二次提示
    if (res.result.status == 1) {
      wx.showModal({
        title: "提示",
        content: "该订单商品需要到店自提，请确认自提点：" + res.result.shopVo.shopName,
        showCancel: true,
        cancelText: "取消订单",
        confirmText: "确认订单",
        success: mRes => {
          if (!mRes.confirm) {
            //取消订单，返回页面
            this.requestToOrderCancel(res.result.id);
          }
        }
      });
    }
  },

  // 处理返回的优惠券数据
  handleOrderCouponData(res) {
    let info = res.result;
    let isCouponShow = info.coupons && info.coupons.length > 0;
    this.setData({
      newUserCouponInfo: info,
      isCouponViewShow: isCouponShow,
      containerTouchmove: isCouponShow ? 'preventTouchMove' : ''
    });
  },

  //检查是否显示取消按钮
  checkIsCancelBtnShow: function (item) {
    let tmpCancelShow = false;
    if (item.status == 3) {
      let nowDate = new Date().getTime();
      let timeObj = common_js.timestampToTime(nowDate);
      let payTimeDateStr = item.payTime.split(" ")[0];
      let currentDateStr = timeObj.year + '-' + timeObj.month + '-' + timeObj.day;
      if (payTimeDateStr == currentDateStr && timeObj.hour < 23) {
        tmpCancelShow = true;
      }
    } else if (item.status == 1) {
      //代付款
      tmpCancelShow = true;
    }
    return tmpCancelShow;
  },

  //取消订单
  requestToOrderCancel: function (orderId) {
    let data = {
      cityId: this.data.userInfo.ztd.cityId,
      code: user_js.getCode(),
      orderId: orderId,
      shopId: this.data.userInfo.ztd.id
    }
    api.wxRequest(url_js.orderCancelUrl, data).then(res => {
      this.handleOrderCancelData(res, orderId);
    }).catch(err => {
      common_js.log(err);
    });
  },

  //处理取消订单的数据
  handleOrderCancelData: function (res, orderId) {
    common_js.showToast("订单已取消");
    //刷新当前页面
    this.requestToGetOrderInfo(this.data.orderId);
    //通知上个页面也刷新页面
    this.prePageRefreshData();
  },

  //通知上个页面也刷新页面
  prePageRefreshData: function () {
    if (this.data.orderListStatus) {
      let pages = getCurrentPages();
      let prePage = pages[pages.length - 2];
      prePage.onPullDownRefresh();
    }
  },

  //删除订单
  requestToOrderDelete: function (orderId) {
    let data = {
      cityId: this.data.userInfo.ztd.cityId,
      code: user_js.getCode(),
      orderId: orderId,
      shopId: this.data.userInfo.ztd.id
    }
    api.wxRequest(url_js.orderDeleteUrl, data).then(res => {
      this.handleOrderDeleteData(res, orderId);
    }).catch(err => {
      common_js.log(err);
    });
  },

  //处理删除订单的数据
  handleOrderDeleteData: function (res, orderId) {
    //1.提示
    common_js.showToast("订单已删除");
    //2.通知上个页面也刷新页面
    this.prePageRefreshData();
    //3.返回上个页面
    wx.navigateBack({});
  },

  //生成预支付订单
  requestToPayPrepare: function (orderId) {
    let data = {
      cityId: this.data.userInfo.ztd.cityId,
      code: user_js.getCode(),
      orderId: orderId,
      shopId: this.data.userInfo.ztd.id,
    }
    api.wxRequest(url_js.payPrepareUrl, data).then(res => {
      this.handlePayPrepareData(res, orderId);
    }).catch(err => {
      common_js.log(err);
    });
  },

  //处理生成预支付订单数据
  handlePayPrepareData: function (res, orderId) {
    let payItem = res.result;
    //微信支付
    wx.requestPayment({
      timeStamp: payItem.timeStamp,
      nonceStr: payItem.nonceStr,
      package: payItem.package,
      signType: payItem.signType,
      paySign: payItem.paySign,
      success: res => {
        //刷新页面
        this.handleOrderCancelData();
      },
      fail: res => {
        if (common_js.containsKeyString(res.errMsg, "fail cancel")) {
          //什么也不做
        } else {
          common_js.showToast(res.errMsg);
        }
      }
    })
  },

  //获取顶部描述信息
  getTopDes: function (item) {
    let text = '';
    //拼团中
    if (item.type == 3) {
      if (item.groupBuyStatus == 0) {
        text = "拼团中";
      } else if (item.groupBuyStatus == 1) {
        text = "拼团成功";
      } else if (item.groupBuyStatus == 2) {
        text = "拼团失败";
      }
    }

    return text;
  },

  // 打开地图
  onMap() {
    // 获取设置
    wxp.openLocation({
      latitude: this.data.item.shopVo.geoLat,
      longitude: this.data.item.shopVo.geoLon
    }).then(res => {}).catch(err => {})
  },

  // showAlert 
  showPhoneView() {
    this.setData({
      containerTouchmove: 'preventTouchMove',
      isPhoneShow: true
    });
  },

  //联系团长
  contactDz: function (e) {
    if (!this.data.item.shopVo.mobile) {
      common_js.showToast("电话不存在！");
      return
    }
    // dismiss
    this.onHidePhoneView();
    //打电话
    wx.makePhoneCall({
      phoneNumber: this.data.item.shopVo.mobile
    })
  },

  //复制订单号
  onCopyOrder: function (e) {
    if (!this.data.item || !this.data.item.billNo) {
      common_js.showToast("订单编号不存在");
      return;
    }
    wx.setClipboardData({
      data: this.data.item.billNo
    })
  },

  //删除订单
  onDelete: function (e) {
    this.requestToOrderDelete(this.data.orderId);
  },

  //去支付
  onBuy: function (e) {
    this.requestToPayPrepare(this.data.orderId);
  },

  //取消订单
  onCancel: function (e) {
    common_js.showModal("是否确认取消订单？", null, true, "放弃", "取消订单", () => {
      this.requestToOrderCancel(this.data.orderId);
    });
  },

  //售后详情
  onAfterSale: function (e) {
    wx.navigateTo({
      url: '../myOrderAfterSaleDetail/myOrderAfterSaleDetail?orderId=' + this.data.orderId
    })
  },

  //拼团详情
  onPintDetail: function (e) {
    //跳转到团详情
    wx.navigateTo({
      url: '../myPintuaDetail/myPintuaDetail?groupId=' + this.data.item.groupId
    });
  },

  // 弹框
  //按钮点击事件
  //禁止滚动
  preventTouchMove: function () {},

  // 监听用户滑动页面事件
  onPageScroll: function (e) {
    let topY = e.scrollTop + "px";
    this.setData({
      pageScrollTop: topY
    });
  },

  //隐藏商品属性页面
  onHidePhoneView: function (e) {
    this.setData({
      containerTouchmove: '',
      isPhoneShow: false
    });
  },

  // 新人多重好礼
  onNewUserAlertCheck() {
    this.onNewUserAlertClose();
    wx.navigateTo({
      url: '/pages/myDiscount/myDiscount'
    })
  },
  onNewUserAlertUse() {
    this.onNewUserAlertClose();
    wx.switchTab({
      url: '../category/category'
    });
  },

  onNewUserAlertClose() {
    this.setData({
      containerTouchmove: '',
      isCouponViewShow: false
    });
  },
})